<template>
  <el-dialog v-if="load" :title="title" v-model="visible" align-center width="800px" destroy-on-close @close="handleClose" :close-on-click-modal="false">
    <el-form :model="formData" label-width="220px" :rules="rules" ref="ruleFormRef" class="formw200">
      <el-form-item label="规则名称:" prop="strategy_name">
        <el-input v-model="formData.strategy_name" class="input" placeholder="规则名称" />
      </el-form-item>
      <el-form-item label="优先级:">
        <VXSelect v-model="formData.priority_level" class="input" placeholder="数字越大优先级越高" dictionary="order_strategy_order_priority" />
        <span class="ml-2">数字越大，优先级越高！</span>
      </el-form-item>
      <el-form-item label="站点:">
        <el-select class="input" multiple v-model="formData.sites" filterable collapse-tags clearable placeholder="站点" @change="sitesChange">
          <el-option v-for="(d, i) in sitesOpt" :key="i" :label="d.site_name" :value="d.site_id"></el-option>
        </el-select>

        <el-button type="primary" class="ml-4" @click="handleSelectAll('sites')">全选</el-button>
      </el-form-item>

      <el-form-item label="店铺:">
        <el-select class="input" multiple v-model="modelBindValue.shop" filterable collapse-tags clearable placeholder="店铺" @change="shopChange">
          <el-option v-for="(d, i) in shopOpt" :key="i" :label="d.shop_name" :value="d.shop_id"></el-option>
        </el-select>

        <el-button type="primary" class="ml-4" @click="handleSelectAll('shop')">全选</el-button>
        <el-link v-show="formData.shop && formData.shop.length" type="danger" @click="handleClearItem('shop', null)" class="ml-2" :underline="false"> 清除 </el-link>
        <div class="mt-[8px] w-[100%]">
          <div class="del-box">
            <div class="item flex justify-between" :key="item.shop_id" v-for="(item, index) in formData.shop">
              <span>{{ item.shop_name }}</span>
              <svg-icon icon-class="close_red" @click="handleClearItem('shop', index)" style="color: #e61323" />
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="收货国家:">
        <SelectCountry multiple collapse-tags clearable filterable ref="SelectCountryRef" style="width: 320px" v-model="modelBindValue.countryIds" labelKey2="true" />
        <div class="mt-[8px]">
          <div class="del-box">
            <div class="item flex justify-between" :key="item.country_name" v-for="(item, index) in formData.country">
              <span>{{ item.country_name }}</span>
              <svg-icon icon-class="close_red" @click="handleClearItem('countryIds', index)" style="color: #e61323" />
            </div>
          </div>
          <el-link v-show="formData.country && formData.country.length" type="danger" @click="handleClearItem('countryIds', null)" class="ml-2" :underline="false"> 清除 </el-link>
        </div>
      </el-form-item>

      <el-form-item label="发货仓库:">
        <VXSelect :list="optionsList.warehouse" multiple collapse-tags clearable filterable style="width: 320px" v-model="modelBindValue.warehouseModel" />
        <div class="mt-[8px]">
          <div class="del-box">
            <div class="item flex justify-between" :key="item.country_name" v-for="(item, index) in formData.shipping_warehouse">
              <span>{{ item.warehouse_name }}</span>
              <svg-icon icon-class="close_red" @click="handleClearItem('warehouseModel', index)" style="color: #e61323" />
            </div>
          </div>
          <el-link v-show="formData.shipping_warehouse && formData.shipping_warehouse.length" type="danger" @click="handleClearItem('warehouseModel', null)" class="ml-2" :underline="false">
            清除
          </el-link>
        </div>
      </el-form-item>

      <el-form-item label="运输方式:">
        <SelectShippingMethod class="input" multiple collapse-tags clearable filterable ref="SelectShippingMethodRef" v-model="modelBindValue.shippingMethod" placeholder="运输方式" />
        <div class="mt-[8px]">
          <div class="del-box">
            <div class="item flex justify-between" :key="item.shipping_id" v-for="(item, index) in formData.shipping_method">
              <span>{{ item.shipping_name }}</span>
              <svg-icon icon-class="close_red" @click="handleClearItem('shippingMethod', index)" style="color: #e61323" />
            </div>
          </div>
          <el-link v-show="formData.shipping_method && formData.shipping_method.length" type="danger" @click="handleClearItem('shippingMethod', null)" class="ml-2" :underline="false"> 清除 </el-link>
        </div>
      </el-form-item>

      <el-form-item label="订单商品:" class="mb-[8px]">
        <el-button type="primary" @click="() => (visibleProductSku = true)">添加产品</el-button>
      </el-form-item>
      <el-form-item>
        <div class="del-box">
          <div class="item flex justify-between" :key="item" v-for="(item, index) in formData.product_sku">
            <span>{{ item }}</span>
            <svg-icon icon-class="close_red" @click="handleDelProductSku(item, index)" style="color: #e61323" />
          </div>
        </div>
        <el-link v-show="formData.product_sku && formData.product_sku.length" type="danger" @click="handleDelProductSku" class="ml-2" :underline="false"> 清除 </el-link>
      </el-form-item>

      <el-form-item label="订单状态:">
        <VXSelect dictionary="order_status" placeholder="订单状态" multiple collapse-tags v-model="formData.order_status" />
      </el-form-item>
      <el-form-item label="订单金额:" style="width: 577px">
        <el-col :span="9">
          <el-form-item prop="lowest_selling_price">
            <DkInputNumber v-model="formData.order_amount_start" :precision="2" :controls="false" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col class="text-center" :span="2">
          <span class="text-gray-500">-</span>
        </el-col>
        <el-col :span="9">
          <el-form-item prop="highest_selling_price">
            <DkInputNumber v-model="formData.order_amount_end" :precision="2" :controls="false" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col class="text-center" :span="3">
          <span>RMB</span>
        </el-col>
      </el-form-item>

      <el-form-item label="是否拆分订单:">
        <el-select v-model="formData.is_split_order" clearable>
          <el-option :value="1" label="是" />
          <el-option :value="0" label="否" />
        </el-select>
      </el-form-item>

      <el-form-item label="执行时间：">
        <div class="executionTime" v-for="(item, i) in formData.execution_time" :key="i">
          <div class="center">
            <el-checkbox v-model="item.is_execution" label="1" :true-value="1" :false-value="0" size="large">{{ item.week }} </el-checkbox>
          </div>
          <div class="select">
            <el-select style="width: 100px" v-model="item.execution_start">
              <el-option v-for="(item, i) in timeOption" :value="item" :key="i">{{ item }}</el-option>
            </el-select>
            <span class="ml-2 mr-2">-</span>
            <el-select style="width: 100px" v-model="item.execution_end">
              <el-option v-for="(item, i) in timeOption" :value="item" :key="i">{{ item }}</el-option>
            </el-select>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="执行条件：">
        <el-radio-group v-model="formData.execution_condition" @change="conditionRadio" class="block-radio">
          <!-- <el-radio :label="0">未选择执行条件</el-radio> -->
          <el-radio :label="1"
            >在订单最晚发货时间
            <el-input style="width: 100px" type="number" v-model="formData.execution_condition_time['1']" placeholder="请输入" />
            小时标记发货
          </el-radio>
          <el-radio :label="2">真实发货后立刻标记发货</el-radio>
          <el-radio :label="5">有真实追踪号后立即标发</el-radio>
          <el-radio :label="3"
            >在订单的支付时间加
            <el-input style="width: 100px" type="number" v-model="formData.execution_condition_time['3']" placeholder="请输入" />
            小时标记发货
          </el-radio>
          <el-radio :label="4"
            >在订单的拉单时间加
            <el-input style="width: 100px" type="number" v-model="formData.execution_condition_time['4']" placeholder="请输入" />
            小时标记发货
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-divider class="divider" border-style="dashed"> 满足以上条件时，执行以下操作 </el-divider>
      <el-form-item>
        <el-radio-group v-model="formData.marking_method" class="block-radio">
          <!-- <el-radio :label="0">请选择标发方式</el-radio> -->
          <el-radio :label="1">只上传真实追踪号</el-radio>
          <el-radio :label="2">可上传本地追踪号</el-radio>
          <el-radio :label="3">空追踪号标记发货</el-radio>
          <el-radio :label="4">自动标记发货，ERP不操作</el-radio>
          <el-radio :label="5">只上传本地追踪号</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态：">
        <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">保 存 </el-button>
    </template>
    <SelectProduct v-model:visible="visibleProductSku" :multiple="true" :selectIds="formData.product_sku" @uploadSku="handleProductSku" />
  </el-dialog>
</template>

<script setup>
// 组件操作卡顿  待优化
import { reactive, toRefs } from "vue"
import api from "../api"
import { ElMessage } from "element-plus"
import SelectCountry from "@/components/Selects/SelectCountry/index.vue"
import SelectProduct from "@/components/SelectProduct/index.vue"
import useCommonStore from "@/store/modules/common"
import { tmsOverallOptions, getShop } from "@/api/public"
import SelectShippingMethod from "@/components/Selects/SelectShippingMethod/index.vue"
import SelectSites from "@/components/Selects/SelectSites/index.vue"
import SelectShop from "@/components/Selects/SelectShop/index.vue"
import { clearObj } from "@/utils"
import { cloneDeep } from "lodash"
import { apiGetPlatformSites } from "@/api/public"
import DkInputNumber from "@/components/DKComponents/InputNumber/index.vue"
const commonStore = useCommonStore()

const sitesOpt = ref([])
const shopOpt = ref([])

const platformChange = async (e) => {
  const { data } = (await apiGetPlatformSites({ platform_ids: [e] })) || {}
  sitesOpt.value = data.map((n) => ({
    site_name: n.site_abbrev,
    site_id: n.site_id,
  }))
}

const sitesChange = async (e, edit = false) => {
  let params = {
    platform_ids: [platformId.value],
    site_ids: e,
  }
  const { data } = (await getShop(params)) || {}
  !edit && (modelBindValue.value.shop = [])
  const _data = data.map((n) => ({
    shop_name: n.shop_name,
    shop_id: n.shop_id,
  }))
  shopOpt.value = _data
  console.log(10099)
}

const shopChange = (e) => {
  formData.value.shop = shopOpt.value.filter((v) => e.includes(v.value))
}

const ruleFormRef = ref()
const load = ref(false)
const platformId = ref(null)
const SelectCountryRef = ref({})
const SelectSitesRef = ref({})
const SelectShopRef = ref({})
const SelectShippingMethodRef = ref({})
const visible = ref(false)
let loadings = reactive({})
const props = defineProps({
  title: {
    type: String,
    default: "新增",
  },
  platform: [String, Number],
})
const timeOption = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
const data = reactive({
  formData: {
    tenant_id: 1,
    strategy_name: "",
    priority_level: 0,
    platform: "amazon",
    sites: [
      // {
      //   "site_id": "1",
      //   "site_name": "US"
      // },
      // {
      //   "site_id": "2",
      //   "site_name": "JP"
      // },
      // {
      //   "site_id": "3",
      //   "site_name": "UK"
      // }
    ],
    shop: [],
    country: [
      // {
      //   "country_id": "1",
      //   "country_name": "美国US"
      // },
      // {
      //   "country_id": "2",
      //   "country_name": "加拿大CA"
      // }
    ],
    shipping_warehouse: [],
    shipping_method: [],
    product_sku: [],
    order_status: [],
    order_amount_start: "",
    order_amount_end: "",
    order_amount_currency: "RMB",
    is_split_order: "",
    execution_time: [
      {
        week: "星期一",
        is_execution: 0,
        execution_end: 24,
        execution_start: 0,
      },
      {
        week: "星期二",
        is_execution: 0,
        execution_end: 24,
        execution_start: 0,
      },
      {
        week: "星期三",
        is_execution: 0,
        execution_end: 24,
        execution_start: 0,
      },
      {
        week: "星期四",
        is_execution: 0,
        execution_end: 24,
        execution_start: 0,
      },
      {
        week: "星期五",
        is_execution: 0,
        execution_end: 24,
        execution_start: 0,
      },
      {
        week: "星期六",
        is_execution: 0,
        execution_end: 24,
        execution_start: 0,
      },
      {
        week: "星期日",
        is_execution: 0,
        execution_end: 24,
        execution_start: 0,
      },
    ],
    execution_condition: 2,
    execution_condition_time: { 1: 6, 3: 6, 4: 6 },
    marking_method: 1,
    status: 1,
    is_delete: 0,
  },
  modelBindValue: {
    countryIds: [],
    warehouseModel: [],
    shippingMethod: [],
    sites: [],
    shop: [],
  },
  isType: false,
})
const { formData, isType, modelBindValue } = toRefs(data)
const { title } = toRefs(props)
const visibleProductSku = ref(false)
const emit = defineEmits(["close", "confirm"])
const optionsList = ref({
  site: [], // 站点
  shop: [], // 店铺
  warehouse: [], // 发货仓库
  shippingMethod: [], // 运输方式
})

const handleProductSku = (list) => {
  formData.value.product_sku = list.map((v) => v.sku)
}

const handleDelProductSku = (value, index) => {
  if (!index && index !== 0) {
    formData.value.product_sku = []
  } else {
    formData.value.product_sku.splice(index, 1)
  }
}

const rules = reactive({
  strategy_name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
})

const handleClearItem = (key, index) => {
  if (!index && index !== 0) {
    modelBindValue.value[key] = []
  } else {
    modelBindValue.value[key].splice(index, 1)
  }
}

watch(
  () => modelBindValue.value.countryIds,
  (dtd) => {
    if (!SelectCountryRef.value || !SelectCountryRef.value.optionsList) return
    const optionsList = SelectCountryRef.value.optionsList
    formData.value.country = dtd.reduce((pre, cur) => {
      const _find = optionsList.find((v) => v.id === cur)
      pre.push({
        country_id: _find.id,
        country_name: `${_find.name} ${_find.country}`,
      })
      return pre
    }, [])
  },
  { deep: true }
)

watch(
  () => modelBindValue.value.warehouseModel,
  (dtd) => {
    const list = optionsList.value.warehouse
    formData.value.shipping_warehouse = dtd.reduce((pre, cur) => {
      const _find = list.find((v) => v.value === cur)
      pre.push({
        warehouse_id: _find.value,
        warehouse_name: _find.label,
      })
      return pre
    }, [])
  },
  { deep: true }
)

watch(
  () => modelBindValue.value.shippingMethod,
  (dtd) => {
    if (!SelectShippingMethodRef.value || !SelectShippingMethodRef.value.optionsList) return
    const list = SelectShippingMethodRef.value.optionsList
    formData.value.shipping_method = dtd.reduce((pre, cur) => {
      const _find = list.find((v) => v.channel_id === cur)
      pre.push({
        shipping_id: cur,
        shipping_name: _find.channel_name,
      })
      return pre
    }, [])
  },
  { deep: true }
)

// watch(() => modelBindValue.value.sites, dtd => {
// console.log(112233);
// console.log(sitesOpt.value);
// console.log(dtd);
// formData.value.sites = sitesOpt.value.filter(v=>dtd.includes(v.site_id))
// console.log(formData.value.sites);
//   // if (!SelectSitesRef.value || !SelectSitesRef.value.optionsList) return
//   // console.log(445566);
//   // const list = SelectSitesRef.value.optionsList
//   // formData.value.sites = dtd.reduce((pre, cur) => {
//   //   const _find = list.find(v => v.site_id === cur)
//   //   pre.push({
//   //     site_id: cur,
//   //     site_name: _find.site_name,
//   //   })
//   //   return pre
//   // }, [])
// }, {deep: true})

watch(
  () => modelBindValue.value.shop,
  (dtd) => {
    formData.value.shop = shopOpt.value.filter((v) => dtd.includes(v.shop_id))
  },
  { deep: true }
)

const handleSelectAll = (type) => {
  switch (type) {
    case "shippingMethod":
      modelBindValue.value.shippingMethod = SelectShippingMethodRef.value.optionsList.map((item) => item.channel_id)
      break
    case "warehouse":
      modelBindValue.value.warehouseModel = optionsList.value.warehouse.map((item) => item.value)
      break
    case "sites":
      formData.value.sites = sitesOpt.value.map((item) => item.site_id)
      break
    case "shop":
      console.log(shopOpt.value)
      modelBindValue.value.shop = shopOpt.value.map((item) => item.shop_id)
      // formData.value.shop = shopOpt.value
      // modelBindValue.value.shop = SelectShopRef.value.optionsList.map(item => item.shop_id)
      break
    default:
      break
  }
}

//执行条件
const conditionRadio = (val) => {
  if (val == 2) {
    formData.value.execution_condition_time = 0
  }
}
//删除店铺
const deleteShop = (arr, obj, index) => {
  arr.splice(index, 1)
}

const echoSelect = (data) => {
  const objs = {
    countryIds: {
      key: "country",
      field: "country_id",
    },
    warehouseModel: {
      key: "shipping_warehouse",
      field: "warehouse_id",
    },
    shippingMethod: {
      key: "shipping_method",
      field: "shipping_id",
    },
    // sites: {
    //   key: 'sites',
    //   field: 'site_id'
    // },
    // shop: {
    //   key: 'shop',
    //   field: 'shop_id'
    // },
  }
  Object.keys(objs).forEach((k) => {
    const { key, field } = objs[k]
    const _target = data[key]
    if (_target && Array.isArray(_target)) {
      modelBindValue.value[k] = _target.reduce((pre, cur) => {
        pre.push(cur[field])
        return pre
      }, [])
    }
  })
}
// 打开弹窗
const open = (row = {}, pId) => {
  if (!load.value) {
    load.value = true
  }
  if (row.id) {
    isType.value = true
    api.detail({ id: row.id }).then(async (res) => {
      platformId.value = res.data.platform
      res.data.sites = res.data.sites.map((v) => v.site_id)
      let execution_condition_time = res.data.execution_condition_time
      res.data.execution_condition_time = {}
      res.data.execution_condition_time[res.data.execution_condition] = execution_condition_time
      res.data.is_split_order = res.data.is_split_order == -1 ? "" : res.data.is_split_order
      formData.value = res.data
      echoSelect(formData.value)
      platformChange(platformId.value)
      await sitesChange(res.data.sites, true)
      modelBindValue.value.shop = res.data.shop.map((v) => v.shop_id)
      loadings = reactive({})
      visible.value = true
    })
  } else {
    platformId.value = pId
    loadings = reactive({})
    isType.value = false
    visible.value = true
    platformChange(platformId.value)
    sitesChange()
  }
}
// 关闭弹窗
const close = () => {
  ruleFormRef.value.resetFields()
  modelBindValue.value = {
    countryIds: [],
    warehouseModel: [],
    shippingMethod: [],
    sites: [],
    shop: [],
  }
  formData.value = clearObj(formData.value)
  formData.value.product_sku = []
  formData.value.execution_condition = 2
  formData.value.marking_method = 1
  formData.value.status = 1

  visible.value = false
}

const handleClose = () => {
  close()
  emit("close")
}
// 提交
const submit = () => {
  let { validate } = ruleFormRef.value
  validate(async (valid) => {
    if (valid) {
      loadings.submit = true
      try {
        const cloneFormData = cloneDeep(formData.value)
        cloneFormData.execution_condition_time = cloneFormData.execution_condition_time[cloneFormData.execution_condition]
        cloneFormData.sites = sitesOpt.value.filter((v) => cloneFormData.sites.includes(v.site_id))
        cloneFormData.order_amount_start = Number(cloneFormData.order_amount_start)
        cloneFormData.order_amount_end = Number(cloneFormData.order_amount_end)
        const dtd = { ...cloneFormData, platform: platformId.value }
        dtd.is_split_order = dtd.is_split_order != 0 && dtd.is_split_order != 1 ? -1 : dtd.is_split_order
        if (isType.value) {
          await api.update(dtd)
        } else {
          await api.create(dtd)
        }
        ElMessage({ message: `保存成功！`, type: "success" })
        setTimeout(() => {
          emit("confirm")
        }, 500)
        close()
      } catch (e) {
        console.warn(e)
      }
      loadings.submit = false
    }
  })
}

const initOptions = async () => {
  optionsList.value.warehouse = await commonStore.getWarehouseOption()
}

onMounted(() => {
  initOptions()
  // sitesChange()
})

defineExpose({ open })
</script>
<style lang="scss" scoped>
.del-box {
  width: 320px;
  height: 100px;
  border-radius: 4px;
  // border: 1px solid #e6e7e9;
  border: 1px solid var(--base-border-color);
  overflow-y: scroll;
  // padding: 14px 12px 16px 16px;
  padding: 8px;
  .item {
    display: flex;
    align-items: center;
    background: #f0f2f5;
    padding: 0 8px;
    margin-bottom: 4px;
    border-radius: 4px;
    height: 28px;
    span {
      color: #333;
    }
  }

  svg {
    cursor: pointer;
  }
}

.formw200 {
  :deep(.input) {
    width: 320px;
  }
}

.w100 {
  width: 100%;
}

.executionTime {
  // border: 1px solid #d9d9d9;
  border: 1px solid var(--base-border-color);
  margin-bottom: 20px;

  &:nth-child(2n) {
    border-left: none;
  }

  .center {
    text-align: center;
  }

  .select {
    padding: 5px;
    // border-top: 1px solid #d9d9d9;
    border-top: 1px solid var(--base-border-color);
  }
}

:deep(input::-webkit-outer-spin-button),
:deep(input::-webkit-inner-spin-button) {
  -webkit-appearance: none !important;
}

:deep(.el-input__inner) {
  line-height: 1px !important;
}
:deep(.block-radio) {
  display: block;
  .el-radio {
    display: block;
    margin-bottom: 8px;
  }
}
:deep(.divider) {
  color: red;
  .el-divider__text {
    color: var(--color-primary);
  }
}
</style>
